package com.giveu.signature.common.document.pdf.itext;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.giveu.common.exception.ResultRuntimeException;
import com.giveu.signature.common.util.FileUtil;
import com.itextpdf.text.DocumentException;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;


public class PdfItextUtil {

	private final static Logger logger = LoggerFactory.getLogger(PdfItextUtil.class);

	/**
	 * 替换pdf中的变量
	 *
	 * @param pdfSourcePath
	 * @param pdfOutPath
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static Map<String, List<ReplaceRegion>> getReplaceRegionAndConvert(String pdfSourcePath, String pdfOutPath, Map<String, String> param) throws Exception {
		PdfReplacer textReplacer = new PdfReplacer(pdfSourcePath);
		if (param != null && !param.isEmpty()) {
			Set<Entry<String, String>> entrySet = param.entrySet();
			for (Entry<String, String> entry : entrySet) {
				textReplacer.replaceTextCheckType(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
			}
		}
		File outFile = new File(pdfOutPath);
		FileUtil.create777File(outFile);
		textReplacer.toPdf(pdfOutPath);
		return textReplacer.getReplaceRegionMap();
	}

	public static byte[] getReplaceRegionAndConvert(String pdfSourcePath, Map<String, String> param) throws Exception {
		PdfReplacer textReplacer = new PdfReplacer(pdfSourcePath);
		if (param != null && !param.isEmpty()) {
			Set<Entry<String, String>> entrySet = param.entrySet();
			for (Entry<String, String> entry : entrySet) {
				textReplacer.replaceTextCheckType(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
			}
		}
		return textReplacer.toBytes();
	}

	public static byte[] getReplaceRegionAndConvert(byte[] pdfSourcePath, Map<String, String> param) throws Exception {
		PdfReplacer textReplacer = new PdfReplacer(pdfSourcePath);
		if (param != null && !param.isEmpty()) {
			Set<Entry<String, String>> entrySet = param.entrySet();
			for (Entry<String, String> entry : entrySet) {
				textReplacer.replaceTextCheckType(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
			}
		}
		return textReplacer.toBytes();
	}

	public static File getFileFromBytes(byte[] b, String outputFile){
		BufferedOutputStream stream = null;
		File file = null;
		try{
			file = new File(outputFile);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e){
			e.printStackTrace();
		} finally{
			if (stream != null){
				try{
					stream.close();
				} catch (IOException e1){
					e1.printStackTrace();
				}
			}
		}
		return file;
	}

	public static void main(String[] args) {
		String pdfSourcePath = "C:\\Users\\520878\\Desktop\\pdf替换工具类\\pdf替换工具类\\117.pdf";
		//        String pdfOutPath = "C:\\Users\\Administrator\\Desktop\\1171.pdf";
		//        Map<String, String> param = new HashMap<>();
		//        param.put("loanAmtUpper","是大三大四的");
		try {
//			String pdfOutPath = "C:\\Users\\520878\\Desktop\\pdf替换工具类\\pdf替换工具类\\1232.pdf";
			Map<String, Object> param = new HashMap<>();
			Map<String, Object> param2 = new HashMap<>();
			param2.put("loanAmt","5000.00");
			param2.put("contractNO","20190929123007100076");
			param2.put("loanDate","2019年09月28日");
			param2.put("sigYear","2019");
			param2.put("sigMonth","09");
			param2.put("sigDay","29");
			param2.put("contractNO1",23242525);
			param.put("param",param2);
			getFileFromBytes(PdfItextUtil.getReplaceRegionAndConverts("D:\\data\\代扣服务授权书1.pdf", param),"D:\\data\\test123.pdf");
			//            getPdfDateAndVerify();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 银行解析的方法
	 * @throws Exception
	 */
	public static void getPdfDateAndVerify() throws Exception {
		PDDocument document = PDDocument.load(new File("C:\\Users\\zhouminghe\\Desktop\\\\1231.pdf"));
		PDFTextStripper tStripper = new PDFTextStripper();
		String pdfFileInText = tStripper.getText(document);
		System.out.println("pdfFileInText = " + pdfFileInText);


	}

	public static byte[] getReplaceRegionAndConverts(String tempPath, Map<String, Object> map) throws IOException, DocumentException {
		PdfReplacer textReplacer = new PdfReplacer(tempPath);
		if (map != null && !map.isEmpty()) {
			Map<String, String> kvMap = getMapString(null,map); 
			for (Entry<String, String> entry : kvMap.entrySet()) {
            	textReplacer.replaceTextCheckType(entry.getKey(),entry.getValue());
			}
		}
		return textReplacer.toBytes();
	}

	private static Map<String, String> getMapString(String prefix,Map<String, Object> map) {
		Map<String, String> kvMap = new HashMap<>();
		for (Entry<String, Object> entry : map.entrySet()) {
			if(entry.getValue() instanceof Map){
				kvMap.putAll(getMapString(prefix==null?entry.getKey():prefix+"."+entry.getKey(),(Map)entry.getValue()));
			}else{
				kvMap.put(prefix==null?entry.getKey():prefix+"."+entry.getKey(), entry.getValue()==null?"":String.valueOf(entry.getValue()));
			}
		}
		return kvMap;
	}

}
